import React from "react";
import videojs from "video.js";
import "video.js/dist/video-js.css";
import style from "./index.less";
import { px2rem } from "../../utils/tools";


var playBtn = require("./playBtn.png");

var timer = null;

var useCanvasPlayer = false;



export default class VideoPlayer extends React.Component {

  state = {
    showBtn: true
  }
  componentDidMount() {
    let self = this;
    if (!this.inIos() && !this.inWX() && !this.inQQ()) {
      //不在微信不在IOS 在各个安卓手机原生浏览器 则使用canvas播放模式
      //canvas 任然不能解决 安卓平台自带浏览器的video劫持，唯一的方法就是用图片播放序列帧
      useCanvasPlayer = true;
    }
    this.player = videojs(this.videoNode, this.props, function onPlayerReady() {
      console.log("视频组件可以使用了");
      self.props.onPlayerReady && self.props.onPlayerReady(this);
    });
    this.watchFullScreen();
    this.player.on("pause", function () {
      console.log("视频暂停播放")
      self.showBtn()
      // if(useCanvasPlayer&&timer){
      //   clearInterval(timer)
      // }
      if(self.props.stopToDo){
        self.props.stopToDo()
      }
    });
    this.player.on("play", function () {
      console.log("视频开始播放")
      console.log(self.props,"self.props.")
      self.hiddenBtn()
      // if(useCanvasPlayer){
      //   self.canvasPlay()
      // }
      
      if(self.props.playToDo){
        self.props.playToDo()
      }
    });

    this.addClickEvent();
    this.player.generalFullPlay = () => {
      //通用全屏播放方法
      if (!this.inIos() && this.inWX()) {
        //微信安卓全屏播放
        this.player.load();
        this.player.requestFullscreen();
        this.player.play();
      } else {
        //ios全屏播放
        this.player.requestFullscreen();
        this.player.play();
        var _this = this;
        var fn = setInterval(() => {
          _this.player.requestFullscreen();
          _this.player.play();
          if (_this.player.readyState() == 4) {
            clearInterval(fn);
          }
        }, 10);
      }
    };

    if(this.props.videoImgCenter){
      //Q2案例项目特殊样式
      this.player.posterImage.eventBusEl_.style.height = `calc(100vh - ${px2rem(110)})`;
    }

  }

  // destroy player on unmount
  componentWillUnmount() {
    if (this.player) {
      this.player.dispose();
    }
  }


  addClickEvent = () => {
    var clicked = false;
    this.videoNode.addEventListener("touchstart", () => {
      //如果播放按钮显示则监听video点击事件暂停
      clicked = true;
    })
    this.videoNode.addEventListener("touchmove", () => {
      //如果播放按钮显示则监听video点击事件暂停
      clicked = false;
    })
    this.videoNode.addEventListener("touchend", () => {
      //如果播放按钮显示则监听video点击事件暂停
      var { showPlayBtn = true } = this.props;
      var { showBtn } = this.state;
      var playing = showPlayBtn && !showBtn;
      var stop = showPlayBtn && showBtn;
      console.log(showPlayBtn, showBtn, playing, clicked)
      if (playing && clicked) {
        this.player.pause();
      }
      if (stop && clicked) {
        this.player.play();
      }
    })
  }

  showBtn = () => {

    setTimeout(() => {
      this.player.posterImage.eventBusEl_.style.visibility = "visible";
      this.player.posterImage.eventBusEl_.style.opacity = "1";
    }, 300)
    this.setState({
      showBtn: true
    })
  }

  hiddenBtn = () => {
    setTimeout(() => {
      this.player.posterImage.eventBusEl_.style.visibility = "hidden";
      this.player.posterImage.eventBusEl_.style.opacity = "0";
    }, 300)
    this.setState({
      showBtn: false
    })
  }

  watchFullScreen = () => {
    const that = this;
    this.player.on("fullscreenchange", function (e) {
      const bool =
        document.fullscreen ||
        document.webkitIsFullScreen ||
        document.mozFullScreen ||
        false;
      if (!bool) {
        that.player.pause();
      }
    });
  };


  inIos = () => { //判断是否在ios中
    var ua = window.navigator.userAgent.toLowerCase();
    return /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent);
  };

  inWX = (origin, target) => { //判断是否在微信中
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
      return true
    }
    return false
  };

  inQQ = (origin, target) => { //判断是否在微信中
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/QQ\/[0-9]/i)){
      return true
    }
    return false
  };


  canvasPlay = () => {
    var canvas = this.canvasNode;
    var context = canvas.getContext("2d");
    var video = this.videoNode;
    timer = setInterval(function () {
      context.drawImage(video, 0, 0, canvas.width, canvas.height);//绘制视频
      console.log("canvasPlay")
    }, 40);
  }


  // wrap the player in a div with a `data-vjs-player` attribute
  // so videojs won't create additional wrapper in the DOM
  // see https://github.com/videojs/video.js/pull/3856
  render() {
    var { showPlayBtn = true, playCallback } = this.props;
    var { showBtn } = this.state;

    var shouldShowBtn = showPlayBtn && showBtn;
    var that = this;

    return (
      <div data-vjs-player>
        <video
          ref={(node) => (this.videoNode = node)}
          className={`video-js ${style.videoPlayer}`}
          style={this.props.style}
          playsInline={true}
          controls={true}
          webkit-playsinline=""
          x5-video-player-type="h5"
        ></video>
        <canvas className="myCanvas" width="400" height="400" ref={(node) => (this.canvasNode = node)}></canvas>
        <div style={{
          width: "100%", height: "100%", color: "#fff", background: "#000", position: "absolute", top: "0px", left: "0px", paddingTop: "20%",
          zIndex: "10", textAlign: "center", display: `${useCanvasPlayer ? "block" : "none"}`
        }}>
          请在微信或者QQ浏览器内打开
          </div>
        <div className={`ownPlayBtn ${shouldShowBtn ? "showOwnPlayBtn" : "hiddenOwnPlayBtn"}`}
          style={{ top: "50%" }}
          onClick={() => {
            if (playCallback) {
              playCallback()
            }
            setTimeout(() => {
              this.player.play();
            }, 100)

          }}>
          <img src={playBtn} alt="" className="ownPlayBtn" />
        </div>
      </div>

    );
  }
}
